//
//  HMStatusPictureView.swift
//  WeiBo14
//
//  Created by HM on 16/3/8.
//  Copyright © 2016年 HM. All rights reserved.
//  微博cell里面的配图控件

import UIKit
import SDWebImage

// 每一个条目之前的间距
private let itemMargin: CGFloat = 5
// 每一个条目的大小
private let itemWH = CGFloat(Int(SCREENW - 2 * HMStatusCellMargin - 2 * itemMargin)/3)

class HMStatusPictureView: UICollectionView {
    

    
    // 可重用标识符
    private let HMStatusPictureViewCellId = "HMStatusPictureViewCellId"
    
    // 当前配图控件显示的配图数据
    var picUrls: [HMStatusPictureInfo]? {
        didSet{
            label.text = "\(picUrls?.count ?? 0)"
            
            // 拿到数据的数量,去设置当前控件(配图控件)的大小
            // 要考虑到复用的问题,要使用 update
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(self.sizeWithCount(picUrls?.count ?? 0))
            }
            
            // 刷新数据
            self.reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 根据图片的张数,计算当前控件的大小
    ///
    /// - parameter count: 图片的张数
    ///
    /// - returns: 控件的大小
    private func sizeWithCount(count: Int) -> CGSize {
        
        
        if count == 1 {
            // 1. 取到缓存的图片
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(picUrls!.first?.thumbnail_pic) {
                
                var size = image.size
                
                // 如果 size 的宽度低于80.那把就把宽度调整到80,并且高度等比例拉伸
                // 过窄
                if size.width < 80 {
                    size.height = 80 / size.width * size.height
                    size.width = 80
                }
                
                
                // 设置itemSize的大小
                // 设置条目的大小
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = size
                // 2. 返回该图片的大小
                return size
            }
        }
        
        // 设置条目的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        
        // 每一个item之前的间距
        // let itemMargin: CGFloat = 5
        
        // 1. 计算出每一张图片多大
        // let itemWH = CGFloat(Int(SCREENW - 2 * HMStatusCellMargin - 2 * itemMargin)/3)
        
        // 2. 计算出有多少列和多少行
        let col = count == 4 ? 2 : (count > 3 ? 3 : count)
        let row = (count - 1) / 3 + 1
        
        // 3. 根据列数和行数,计算整个配图视图的大小
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    
    // 设置视图
    private func setupUI(){
        // 自己成为自己的数据源
        self.dataSource = self
        self.delegate = self
        // 注册cell
        registerClass(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellId)
        // 设置条目的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        // 设置最小间距 
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
//        // 设置随机色
//        backgroundColor = RandomColor()
        
        addSubview(label)
        
        label.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }

    
    // MARK: - 懒加载控件
    
    private lazy var label: UILabel = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 35)
}

extension HMStatusPictureView: UICollectionViewDataSource {
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    // 返回cell的方法
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓存里面取出cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMStatusPictureViewCellId, forIndexPath: indexPath) as! HMStatusPictureViewCell
        // cell.backgroundColor = RandomColor()
        // 设置数据
        cell.pictureInfo = picUrls![indexPath.item]
        return cell
    }
}

extension HMStatusPictureView: UICollectionViewDelegate {
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        /**
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        browser.sourceImagesContainerView = self; // 原图的父控件
        browser.imageCount = self.photoItemArray.count; // 图片总数
        browser.currentImageIndex = button.tag;
        browser.delegate = self;
        [browser show];

        */
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = picUrls!.count
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }
}

extension HMStatusPictureView: SDPhotoBrowserDelegate {
    
    
    /// 返回占位图片的代理方法
    ///
    /// - parameter browser: <#browser description#>
    /// - parameter index:   <#index description#>
    ///
    /// - returns: <#return value description#>
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        // 1. 取到 index 对应的cell
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as? HMStatusPictureViewCell
        // 2. 取到cell的imageView --> imageView.image
        return cell?.imageView.image
    }
    
    /// 返回高质量的图片的url
    ///
    /// - parameter browser: <#browser description#>
    /// - parameter index:   <#index description#>
    ///
    /// - returns: <#return value description#>
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        //     NSString *urlStr = [[self.photoItemArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        let urlStr = picUrls![index].thumbnail_pic?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle") ?? ""
        return NSURL(string: urlStr)
        
    }
    
    
    
    
    
}


/// 配图视图显示的cell
class HMStatusPictureViewCell: UICollectionViewCell {
    
    // 单张配图的信息
    var pictureInfo: HMStatusPictureInfo? {
        didSet{
            guard let urlString = pictureInfo?.thumbnail_pic else {
                return
            }
            // 显示数据
            imageView.sd_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "timeline_image_placeholder"))
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        // 1.添加子控件
        contentView.addSubview(imageView)
        // 2. 设置约束
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        // 设置imageView的内容模式
        imageView.contentMode = .ScaleAspectFill
        // 把超出控件的内容给删掉
        imageView.clipsToBounds = true
        return imageView
    }()
    
    
}


